#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <inttypes.h>
#include <time.h>
#include <ptcParse.h>
#include <cstring.h>
#include <hexstr.h>
#include <genrand.h>

int pipecmd(const char *cmdstr, char *outstr, int outsize)
{
    FILE *fp = popen(cmdstr, "r");
    if (fp == NULL)
    {
        logerror("Failed to run command: %s", cmdstr);
        return -1;
    }
    if (outstr && outsize > 0)
    {
        memset(outstr, 0, outsize);
        outsize = fread(outstr, outsize, 1, fp);
    }
    else
    {
        outsize = 0;
    }
    pclose(fp);
    return outsize;
}

int main(int argsize, const char **args)
{
    // 如果system函数执行成功，那么它返回0。如果执行失败，那么它会返回-1。
    char tmpbuf[1024] = {0};
    logdebug("system fin:%d", system("sync; ls /"));
    pipecmd("ls /", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("sync", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("tar czvf test.tgz test", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("date +\"%Y-%m-%d %H:%M:%S\"", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("date +\"%Y%m%d%H%M%S\"", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);

    pipecmd("mkdir ./packzip", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("echo abcd > ./packzip/packinf.txt", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("echo `date` > ./packzip/date.txt", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    pipecmd("cat ./packzip/date.txt", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);

    logdebug("system xx:%d", system("xx")); // 0


    logdebug("system subcmd:%d", system("./subcmd")); // 0
    logdebug("system subcmd:%d", system("./subcmd 1")); // other fail
    logdebug("system subcmd:%d", system("./subcmd 1 2")); // other fail
    logdebug("system subcmd:%d", system("./subcmd 1 2 3")); // other fail
    logdebug("system subcmd:%d", system("./subcmd 1 2 3 4 ")); // other fail
    logdebug("system subcmd:%d", system("./subcmd 1 2 3 4 5")); // other fail


    pipecmd("zip -rqP mypswd pack.zip packzip", tmpbuf, sizeof(tmpbuf));
    logdebug("%s", tmpbuf);
    logdebug("system unzip:%d", system("unzip -oqP mypswd pack.zip -d /tmp/"));     // 0 ok
    logdebug("system unzip:%d", system("unzip -oqP mypswx pack.zip -d /tmp/"));     // other fail
    logdebug("system drop_caches:%d", system("echo 1 > /proc/sys/vm/drop_caches")); // other fail


    // pipecmd("unzip -qP mypswd test.zip -d /tmp/", tmpbuf, sizeof(tmpbuf));
    // logdebug("%s", tmpbuf);

    // pipecmd("unzip -nP 123 test.zip -d /tmp/", tmpbuf, sizeof(tmpbuf));
    // logdebug("%s", tmpbuf);

    // logdebug("system unzip:%d", system("unzip -nqP mypswd test.zip -d /tmp/"));// 0成功
    // logdebug("system unzip:%d", system("unzip -nqP 325 test.zip -d /tmp/"));// 执行错误
    return 0;
}